
package com.kweative.lingua.server.controllers;

import com.kweative.lingua.server.Application;
import com.kweative.lingua.server.Controller;
import com.kweative.lingua.server.annotations.MethodInfo;
import com.kweative.model.Table;
import com.kweative.model.data.Row;
import com.kweative.model.data.RowSet;
import java.sql.SQLException;

/**
 *
 * @author henrik
 */
abstract public class CrudController<T extends Table<R,T,?>,R extends Row<T>,A extends Application> extends Controller<A> {
    protected T tbl = null;
    public CrudController(T tbl) {
        super();
        this.tbl = tbl;
    }

    @Override
    @MethodInfo(nonpublic=true)
    public String getName() {
        return tbl.getName();
    }

    @MethodInfo(parms={"filter"})
    public RowSet<R> list(R filter) throws SQLException {
        return list(filter, 0, 30);
    }
    @MethodInfo(parms={"filter","limit"})
    public RowSet<R> list(R filter,int limit) throws SQLException {
        return list(filter, 0, limit);
    }
    @MethodInfo(parms={"filter","offset","limit"})
    public RowSet<R> list(R filter,int offset,int limit) throws SQLException {
        return tbl.select().like(filter).all(offset, limit);
    }

    @MethodInfo(parms={"row"})
    public R save(R data) throws SQLException {
        R result;
        if (data.__primary > 0) {
            tbl.update(data);
            result = data;
        } else {
            int primary = tbl.insert(data);
            result = tbl.select().row(primary).first();
        }
        return result;
    }
    @MethodInfo(parms={"critera"})
    public R get(R criteria) {
        return (R) tbl.select().like(criteria).first();
    }
    @MethodInfo(parms={"row"})
    public boolean remove(R data) throws SQLException {
        tbl.delete(data.__primary).execute();
        return true;
    }
    @MethodInfo(parms={"primary"})
    public boolean remove(int primary) throws SQLException {
        tbl.delete(primary).execute();
        return true;
    }
}
